package top.lixunda.ecommerce.server.good.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;

/**
 * @author Xumda
 * @version time:2019/11/21 11:07
 */
@SuppressWarnings("Duplicates")
@Configuration
public class RedisConfig {

    /**
     * 获取ObjectMapper
     *
     * @return ObjectMapper
     */
    private ObjectMapper getObjectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.registerModule(new JavaTimeModule());
        return objectMapper;
    }

    /**
     * 创建RedisTemplate:用于执行Redis操作的方法
     */
    @Bean
    @ConditionalOnMissingBean(name = "redisTemplate")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        //关联
        template.setConnectionFactory(factory);
        //为key设置序列化器
        template.setKeySerializer(new GenericJackson2JsonRedisSerializer(getObjectMapper()));
        //为value设置序列化器
        template.setKeySerializer(new GenericJackson2JsonRedisSerializer(getObjectMapper()));
        return template;
    }

}
